package cz.data.gateway.api.listener;

import com.alibaba.fastjson.JSONObject;
import cz.data.common.rabbitmq.config.RabbitConstant;
import cz.data.gateway.api.service.IRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
@Slf4j
public class RabbitEventListener {

    @Autowired
    IRouteService routeService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(), //注意这里不要定义队列名称,系统会随机产生
            exchange = @Exchange(value = RabbitConstant.ROUTE_FANOUT_EXCHANGE, type = ExchangeTypes.FANOUT)
    )
    )
    public void gatewayRouteEvent(Message message) {
        RouteDefinition routeDefinition = JSONObject.parseObject(message.getBody(), RouteDefinition.class);
        Map<String, Object> metadata = Optional.ofNullable(routeDefinition.getMetadata()).orElseGet(HashMap::new);
        if (Boolean.TRUE.equals(metadata.get("_active"))) {
            log.info("网关接受到路由变更事件,更新路由");
            routeService.save(routeDefinition);
        } else {
            log.info("网关接受到路由变更事件,删除路由");
            routeService.delete(routeDefinition.getId());
        }
    }
}
